package redisgw

import (
	"crypto/rand"
	"fmt"
	"fronter/config"
	"math/big"
	"os"
	"time"

	"github.com/sirupsen/logrus"
)

func init() {

}

//清除hset中的此服务
func TryToClearDeadSvr(SvrName string, SvrWithId string, SvrAddress string) {
	logrus.Infoln("try to clear dead svr:", SvrName, ", address:", SvrAddress)
	HDel(SvrName, SvrAddress)
	HDel(gKeyServerList, SvrWithId)
}

//解析名字到ip port
func Svr(SvrName string) (string, string) {
	//1. 拿所有svr
	allSvr := HGetall(SvrName)
	if len(allSvr) == 0 {
		logrus.Warning("no svr:", SvrName, " online!")
		return "", ""
	}
	idx, _ := rand.Int(rand.Reader, big.NewInt(int64(len(allSvr))))
	//random get a svr
	logrus.Infoln(allSvr)
	var i int = 0
	for svrAddr, svrWithId := range allSvr {
		if i == int(idx.Int64()) {
			return svrAddr, svrWithId
		}
		i++
	}
	logrus.Warningln("unknown error, please check!")
	return "", ""
}

func getServerId() string {
	sid := IncrBy(gKeyServerId, 1)
	if sid == "" {
		logrus.Errorln("get svrid failed! exit!")
		os.Exit(-1)
	}
	return sid
}

func addSvrToList(svrKey string) error {
	if HSet(gKeyServerList, svrKey, "1") != nil {
		logrus.Errorln("add svr:", svrKey, " to list failed!")
		return myerr
	}
	return nil
}

func RegisterSvr(Port uint32) {
	svrName := config.Get().SvrName
	svrIp := config.Get().SvrIp //注册ip，可以指定外网ip
	if svrIp == "" {
		svrIp = "0.0.0.0"
	}
	svrId := getServerId()

	svrRedisKey := getSvrKey(svrName, svrId)
	if HSet(svrName, fmt.Sprintf("%s:%d", svrIp, Port), svrRedisKey) != nil {
		logrus.Errorln("register svr failed at hset!")
		os.Exit(-2)
	}
	if Expire(svrName, 60) != nil {
		logrus.Errorln("expire failed!")
		os.Exit(-2)
	}
	if addSvrToList(svrRedisKey) != nil {
		logrus.Errorln("add svr to list failed!")
		os.Exit(-2)
	}
	logrus.Info("success register to redis! key:", svrRedisKey, " start to ping every 10s.")
	go func() {
		for {
			time.Sleep(time.Second * time.Duration(10))
			Expire(svrName, 60)
			logrus.Infoln("ping to redis, key:", svrName)
			if HSet(svrName, fmt.Sprintf("%s:%d", svrIp, Port), svrRedisKey) != nil {
				logrus.Errorln("register svr failed at hset!")
			}
			if Expire(svrName, 60) != nil {
				logrus.Errorln("expire failed!")
			}
		}
	}()
}
